package com.u2ds.core.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.ui.context.ThemeSource;
import org.springframework.ui.context.support.ResourceBundleThemeSource;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.theme.CookieThemeResolver;
import org.springframework.web.servlet.theme.ThemeChangeInterceptor;

@Configuration
@ConditionalOnWebApplication
public class ThemesConfig extends WebMvcConfigurerAdapter implements EnvironmentAware {
	private Environment env;

	@Override
	public void setEnvironment(Environment environment) {
		this.env = environment;
	}

	@Bean
	public ThemeSource themeSource() {
		ResourceBundleThemeSource rts = new ResourceBundleThemeSource();
		rts.setBasenamePrefix(env.getProperty("spring.theme.source", "themes/"));
		return rts;
	}

	@Bean(name = DispatcherServlet.THEME_RESOLVER_BEAN_NAME)
	@ConfigurationProperties(prefix = "spring.theme.cookie")
	public CookieThemeResolver themeResolver() {
		CookieThemeResolver ctr = new CookieThemeResolver();
		ctr.setDefaultThemeName("default");
		ctr.setCookieName(env.getProperty("spring.theme.cookieName", "me.theme"));
		return ctr;
	}

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		final LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
		localeChangeInterceptor.setParamName("locale");

		registry.addInterceptor(localeChangeInterceptor);

		final ThemeChangeInterceptor themeChangeInterceptor = new ThemeChangeInterceptor();
		themeChangeInterceptor.setParamName(env.getProperty("spring.theme.intperceptor.name", "theme"));

		registry.addInterceptor(themeChangeInterceptor);
	}
}
